﻿namespace WP7Contrib.Logging.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Linq;

    public sealed class DirectoryHelper : IDisposable
    {
        private IList<string> directories = new List<string>();

        public void Dispose()
        {
            if (this.directories != null)
            {
                foreach (var directory in this.directories)
                {
                    if (IsolatedStorageFile.GetUserStoreForApplication().DirectoryExists(directory))
                    {
                        var directoryFiles = Path.Combine(directory, "*.*");
                        var localDirectory = directory;
                        foreach (var filePath in IsolatedStorageFile.GetUserStoreForApplication().GetFileNames(directoryFiles).Select(file => Path.Combine(localDirectory, file)))
                        {
                            Debug.WriteLine("Deleting file - " + filePath);
                            IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(filePath);
                        }

                        IsolatedStorageFile.GetUserStoreForApplication().DeleteDirectory(directory);
                    }
                }
                
                this.directories = null;
            }
        }

        public string GenerateDirectoryName()
        {
            var directory = Guid.NewGuid().ToString();
            this.directories.Add(directory);

            return directory;
        }
    }
}